<template>
  <div>
<div class="index-map" id="index-map">
</div>
<div class="input-card">
     <h4>轨迹回放控制</h4>
     <div class="input-item">
       <input type="button" class="btn" value="保存路线" id="start" @click="savecar()" />
     </div>
     <div class="input-item">
       <input type="button" class="btn" value="开始动画" id="start" @click="startAnimation()" />
       <input type="button" class="btn" value="暂停动画" id="pause" @click="pauseAnimation()" />
     </div>
     <div class="input-item">
       <input type="button" class="btn" value="继续动画" id="resume" @click="resumeAnimation()" />
       <input type="button" class="btn" value="停止动画" id="stop" @click="stopAnimation()" />
       <input type="button" class="btn" value="报警" id="stop" @click="alarm()" />
     </div>
   </div>
   <el-dialog title="保存模拟路线" :visible.sync="dialogFormVisible">
  <el-form :model="carpath">
    <el-form-item label="模拟表联查id" :label-width="formLabelWidth">
      <el-input v-model="carpath.pathCodeId" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="路线名称" :label-width="formLabelWidth">
      <el-input v-model="carpath.pathName" autocomplete="off"></el-input>
    </el-form-item>

  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="savetAnimation()">保存</el-button>
  </div>
</el-dialog>

 </div>
</template>
<script>
 // import {addCar} from '@/api/system/car';
//  window.addEventListener("touchmove", handler, { passive: true });
export default {

data() {

 return {
  carpath:{

  },
  formLabelWidth: '120px',
  dialogFormVisible:false,
   map: {}, //保存地图对象
   marker: null,
   point:"",
   timerId:"",
   timer:"",
   leftStart: "",
   leftStartMark: {}, // 起点的点标记
   leftEnd: "",
   leftEndMark: {}, // 终点的点标记
   typeBtnLeft: false, // 起点终点的点击切换
   leftPath: [], // 路线绘制起点-终点集合
   leftResultPath: [], // 点位路径集合
   lineArr:JSON.parse(window.localStorage.getItem("coord")),
   path:[[116.477525,39.998254],[116.481098,39.998098],[116.479617,39.99615],[116.476667,39.997136]],
   pathCoord:"",//模拟路线坐标
   pointpath:"",//实时坐标
 };
},
mounted() {
 setTimeout(() => {
   this.createMap(); //异步加载（否则报错initMap is not defined）

 }, 1000);

},

methods: {
   //保存路线
  savecar(){
    this.dialogFormVisible=true;
  },
  // 添加路线到模拟路线表
  savetAnimation(){
    this.carpath.pathCoord= this.leftRoute.pathCoord
    console.log(this.carpath)
    addCar(this.carpath).then(resp=>{
      window.localStorage.setItem("pathcoord",this.leftRoute.pathCoord);
       alert("添加路线成功");
       this.open = false;
    })
  },
 // 创建地图
 createMap() {
   let that = this;
   this.$nextTick(() => {
     //地图加载
     that.map = new AMap.Map("index-map", {
       zooms: [8, 20],
       zoom: 10,
       center: [116.764562, 38.061525]
     });
     // 创建点标记
     AMapUI.loadUI(["overlay/SimpleMarker"], function(SimpleMarker) {
       that.leftStartMark = new SimpleMarker({
         //设置节点属性
         iconLabel: {
           //普通文本
           innerHTML: "起",
           style: {
             color: "#fff",
             fontSize: "100%",
             marginTop: "1px"
           }
         },
         iconStyle: "red"
       });
       // 创建左边结束点
       that.leftEndMark = new SimpleMarker({
         //设置节点属性
         iconLabel: {
           //普通文本
           innerHTML: "终",
           style: {
             color: "#fff",
             fontSize: "100%",
             marginTop: "1px"
           }
         },
         iconStyle: "red"
       });
     });
     //获取鼠标点击的经纬度信息
     that.map.on("click", function(e) {
       // 线路点（起点-终点）
       if (that.typeBtnLeft == false) {
         // 先点击起点
         if (that.leftStartMark) {
           that.leftStart = e.lnglat.getLng() + "," + e.lnglat.getLat();
           that.leftStartMark.setMap(that.map);
           that.leftStartMark.setPosition([
             e.lnglat.getLng(),
             e.lnglat.getLat()
           ]);
         }
         // 然后决定终点
         that.typeBtnLeft = true;
       } else if (that.typeBtnLeft == true) {
         // 设置好终点
         if (that.leftEndMark) {
           that.leftEnd = e.lnglat.getLng() + "," + e.lnglat.getLat();
           that.leftEndMark.setMap(that.map);
           that.leftEndMark.setPosition([
             e.lnglat.getLng(),
             e.lnglat.getLat()
           ]);
         }
         // 终止点击
         that.typeBtnLeft = null;
         // 绘制路线
         that.createLeftLine();
       } else {
         console.log("点击完毕");
       }
     });
     this.marker = new AMap.Marker({
         map: this.map,
         position: [116.478935, 39.997761],
         icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
         offset: new AMap.Pixel(-26, -15),
         autoRotation: true,
         angle: -90
       });

     // })
     let polyline = new AMap.Polyline({
         map: this.map,
         path: this.lineArr,
         showDir: true,
         strokeColor: "#28F", //线颜色
         // strokeOpacity: 1,     //线透明度
         strokeWeight: 6 //线宽
         // strokeStyle: "solid"  //线样式
       });
       let passedPolyline = new AMap.Polyline({
         map: this.map,
         // path: this.lineArr,
         strokeColor: "#AF5", //线颜色
         // strokeOpacity: 1,     //线透明度
         strokeWeight: 6 //线宽
         // strokeStyle: "solid"  //线样式
       });
       this.marker.on("moving", function (e) {
         // this.point="";
         passedPolyline.setPath(e.passedPath);
         // console.log(e.passedPath+"")
         // console.log(e.passedPath[e.passedPath.length-1]+"");
         let point1=e.passedPath[e.passedPath.length-1]+"";
         that.point=point1;
        //  console.log(e.passedPath)
         this.pointpath=[
         e.passedPath[e.passedPath.length-1].lng,
         e.passedPath[e.passedPath.length-1].lat,
         ]
        //  console.log(this.pointpath)

       });
       var point1=  this.marker.getPosition();
       // this.point=point1;
       // console.log(this.point)
       var isPointInRing = AMap.GeometryUtil.isPointInRing(point1,this.path);
       this.marker.setLabel({
        //  content:isPointInRing?'内部':'外部',
         offset:new AMap.Pixel(20,0)
     });
       this.map.setFitView();

   });
 },
 alarm(){
    let point=this.marker.pointpath;
    let boolean=AMap.GeometryUtil.isPointInRing(point,this.lineArr);
    if(boolean){

    }else{
        this.$message.error("小车驰离围栏")
    }
    console.log(boolean)
 },

 // 绘制路径-左
 createLeftLine() {
   let that = this;
   if (that.leftStartMark && that.leftEndMark) {
     that.leftStartMark.setMap(null);
     that.leftEndMark.setMap(null);
   }
   //绘制左边初始路径，起点-终点
   that.leftPath = [];
   that.leftPath.push(that.leftStart.split(","));
   that.leftPath.push(that.leftEnd.split(","));
   // 使用DragRoute插件-构造拖拽导航类
   that.map.plugin("AMap.DragRoute", function() {
     that.leftRoute = new AMap.DragRoute(
       that.map,
       that.leftPath,
       AMap.DrivingPolicy.LEAST_TIME,
       {
         showTraffic: false,
         polyOptions: {
           strokeColor: "#409EFF"
         }
       }
     );
     //查询导航路径并开启拖拽导航
     that.leftRoute.search();
     // 监听完成情况
     that.leftRoute.on("complete", function(result) {
       // 移动起始点后自动改变当前经纬度
       that.leftStart =
         result.data.start.location.lng +
         "," +
         result.data.start.location.lat;
       that.leftEnd =
         result.data.end.location.lng + "," + result.data.end.location.lat;
       // 保存点路径集合
        that.leftResultPath = that.leftRoute.getRoute();
        console.log(that.leftResultPath)
        var routePath=[];
        //循环遍历
        that.leftResultPath.forEach(value=>{
          routePath.push([value.lng,value.lat])
        })
        //转换字符串类型
        this.pathCoord=JSON.stringify(routePath)
       console.log('leftResultPath',JSON.stringify(routePath));
     });
   });
 },
 compute(){
   this.timerId = setInterval(() => {
     console.log(this.point);
    this.alarm();
 }, 2000);

 },
      startAnimation() {
       this.marker.moveAlong(this.leftResultPath, 200);
       this.compute()
     },
     pauseAnimation() {
       this.marker.pauseMove();
       console.log(this.point)
     },
     resumeAnimation() {
       this.marker.resumeMove();
     },
     stopAnimation() {
       setInterval(() => {
        clearInterval(this.timerId);
       }, 1000);
       this.marker.stopMove();
      //  location.reload();
     },

},

};
</script>
<style >
.index-map {
height: 100vh;
width: 100vw;
}
</style>
